package com.springboot.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.eduservice.entity.EduSubject;
import com.springboot.eduservice.entity.excel.SubjectData;
import com.springboot.eduservice.service.EduSubjectService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {


    public EduSubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        EduSubject eduSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());

        String id = null;
        if (eduSubject == null){
            EduSubject Subject = new EduSubject();
            Subject.setParentId("0");
            Subject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(Subject);
            id = Subject.getId();
        }else {
            id = eduSubject.getId();
        }

            EduSubject twoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), id);
            if (twoSubject == null) {
                EduSubject Subjecttwo = new EduSubject();
                Subjecttwo.setTitle(subjectData.getTwoSubjectName());
                Subjecttwo.setParentId(id);
                subjectService.save(Subjecttwo);
            }


    }
    //判断一级分类是否重复，重复不添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;

    }
    //判断二级分类是否重复，重复不添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
